package club.guadazi.wemarket.controller;

import club.guadazi.wemarket.entity.TUser;
import club.guadazi.wemarket.service.UserService;
import club.guadazi.wemarket.util.PinyinUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Mariaaron on 16/9/2.
 */
@Controller("userController")
@RequestMapping("/user")
public class UserController {
    private final static Log logger = LogFactory.getLog(UserController.class);

    @Resource(name = "userService")
    private UserService userService;

    /**
     * 该注解用于将Controller的方法返回的对象，通过适当的HttpMessageConverter转换为指定格式后，写入到Response对象的body数据区。
     使用时机：
     返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/search.do")
    public List<Map<String, String>> search(ServletWebRequest request) {
        logger.debug("============= begin search");
        String keyword = request.getParameter("keyword");
        List<TUser> list = userService.searchByKeyWord(keyword);
        List<Map<String, String>> result = new ArrayList<>();
        if (list != null) {
            for (TUser tUser : list) {
                HashMap<String, String> map = new HashMap<>();
                map.put("nickName", tUser.getNickName());
                String phoneNumber = tUser.getPhoneNumber();
                if (StringUtils.isNotEmpty(phoneNumber)) {
                    StringBuilder buffer = new StringBuilder(phoneNumber);
                    buffer.replace(4, 8, "****");
                    map.put("phoneNumber", buffer.toString());
                }
                result.add(map);
            }
        }
        logger.debug("============= end search");
        return result;
    }

    @ResponseBody
    @RequestMapping("/getUsers.do")
    public List<TUser> getUsers() {
        return userService.getUsers();
    }

    @ResponseBody
    @RequestMapping("addUser.do")
    public Map<String, String> addUser(TUser user) {
        Map<String, String> map = new HashMap<>();
        String nickName = user.getNickName();
        if (StringUtils.isNotEmpty(nickName)) {
            String spell = PinyinUtil.cn2Spell(nickName);
            user.setOrderField(spell);
        }
        user.setCreatedDate(new Date());
        user.setUpdatedDate(new Date());
        logger.info(user);
        userService.addUser(user);
        map.put("errorMsg", "");
        return map;
    }

    @ResponseBody
    @RequestMapping("destroyUser.do")
    public Map<String, String> destroyUser(int id) {
        Map<String, String> map = new HashMap<>();
        userService.removeUser(id);
        map.put("success", "true");
        return map;
    }

    @ResponseBody
    @RequestMapping("updateUser.do")
    public Map<String, String> updateUser(TUser user) {
        Map<String, String> map = new HashMap<>();
        user.setUpdatedDate(new Date());
        logger.info(user);
        userService.updateUser(user);
        map.put("errorMsg", "");
        return map;
    }
}
